package top.java.oop.designMode.singleton;

public class SingletonTest {
    public static void main(String[] args) {

        Bank b1 = Bank.getBank();
        Bank b2 = Bank.getBank();
        System.out.println(b1 == b2);

        Order o1 = Order.getOrder();
        Order o2 = Order.getOrder();
        System.out.println(o1 == o2);
    }
}



class Bank {

    /**
     *      饿汉式单例模式     线程安全
     */

    private static Bank bank = new Bank();

    private Bank() {

    }

    public static Bank getBank() {
        return bank;
    }

}

class Order {
    /**
     *      懒汉式单例模式     线程不安全
     */

    private static Order order = null;

    private Order() {

    }

    public static Order getOrder() {
        if (order == null) {
            order = new Order();
        }
        return order;
    }
}

class Person {

    /**
     *      懒汉式单例模式     线程安全
     */

    private static Person person = null;

    private Person() {

    }

    //方式一：效率不是最高
    public static Person getPerson() {
        synchronized (Person.class) {
            if (person == null) {
                person = new Person();
            }
            return person;
        }
    }

    //方式二：效率更高
    public static Person getPerson2() {
        if (person == null) {
            synchronized (Person.class) {
                if (person == null) {
                    person = new Person();
                }
            }
        }
        return person;
    }
}
